package di.module;

import com.f2prateek.rx.preferences2.RxSharedPreferences;
import com.google.gson.Gson;
import com.xgggh.redpack.domain.auth.Auth;
import com.xgggh.redpack.utils.AuthManager;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import io.reactivex.functions.Consumer;

@Module
public class AuthModule {

    private static  final Auth auth = new Auth();

    @Provides
    @Singleton
    public static Auth provideAuthToken(RxSharedPreferences sharedPreferences,
                                        Gson gson) {
        sharedPreferences.getString(AuthManager.Token,"{}")
                .asObservable()
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Auth _auth= gson.fromJson(s,Auth.class);
                        if (_auth!=null){
                            auth.setAccessToken(_auth.getAccessToken());
                            auth.setRefreshToken(_auth.getRefreshToken());
                            auth.setExpiresIn(_auth.getExpiresIn());
                            auth.setScope(_auth.getScope());
                            auth.setTokenType(_auth.getTokenType());
                            auth.setAccountId(_auth.getAccountId());
                        }
                    }
                });
        return auth;
    }
}
